package com.codeplex.boomships.Persistence;

import javax.persistence.*;

import java.util.*;

import com.codeplex.boomships.Common.*;

public class PersistenceManager {
	// Singleton
	private static PersistenceManager aPM;

	public static synchronized PersistenceManager getInstance() {
		if (aPM == null) {
			aPM = new PersistenceManager();
		}
		return aPM;
	}

	EntityManagerFactory emf;
	EntityManager em;

	// Constructores.
	private PersistenceManager() {
		try {
			emf = Persistence.createEntityManagerFactory("jpaDS");
			em = emf.createEntityManager();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public synchronized boolean insertPlayer(Player p) {
		boolean ret = false;
		try {
			if(!existsPlayer(p.getUsername())){
				// Comienza la transaccion.
				em.getTransaction().begin();
				em.persist(p);
				// Finaliza la transaccion.
				em.getTransaction().commit();
				ret = true;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return ret;
	}

	public synchronized Player getPlayer(Player p) {
		Player player;
		try{
			em.getTransaction().begin();
			//Se crea la query:
			Query nq = em.createNamedQuery("Player.findByUserAndPass");
			//Se le asignan los parametros:
			nq.setParameter("pUserName", p.getUsername());
			nq.setParameter("pPassword", p.getPassword());
			//Se ejecuta la query:
			player = (Player)nq.getSingleResult();
			em.getTransaction().commit();
		}catch (NoResultException ex){
			player = null;
		}
		return player;
	}
	
	public synchronized boolean existsPlayer(String pUserName){
		boolean ret = true;
		Player p;
		try{
			em.getTransaction().begin();
			//Se crea la query:
			Query nq = em.createNamedQuery("Player.findByUsername");
			//Se le asignan los parametros:
			nq.setParameter("pUserName", pUserName);
			p = (Player)nq.getSingleResult();
			em.getTransaction().commit();
		}catch(NoResultException ex){
			ret = false;
		}
		return ret;
	}
	
	public synchronized boolean updatePlayer(Player p){
		boolean ret = true;
		Player pPlayer;
		try{
			em.getTransaction().begin();
			//Se crea la query:
			Query nq = em.createNamedQuery("Player.findById");
			//Se le asigna el parametro:
			nq.setParameter("pId", p.getId());
			//Se asigna el resultado de la query a la variable declarada:
			pPlayer = (Player)nq.getSingleResult();
			//Se suplanta el resultado obtenido con la referencia al objeto actualizado que se
			//recibe como parametro.
			pPlayer = p;
			//Se actualizan los datos en la BD.
			em.persist(pPlayer);
			em.getTransaction().commit();
		}catch (NoResultException ex){
			ret = false;
		}
		return ret;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
